﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using System.Collections;
using WebUI.Controls;

namespace WebUI
{
    public partial class Product : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            if (!IsPostBack)
            {
                ReloadData();

                //refresh after init data
                RefreshCategoryTree();
                lstProducts.Refresh();
            }
            txtSearchProduct.Focus();

            //Control access
            //if (!SessionUser.Purchase)
            //{
            //    lstProducts.Columns[5].Visible = false;
            //    lstProducts.Columns[10].Visible = false;

            //    btnEditProd.Visible = false;
            //    btnDeleteProd.Visible = false;
            //    btnAddProd.Visible = false;
            //    btnEditCategory.Visible = false;
            //    btnRemoveCategory.Visible = false;
            //    btnAddCategory.Visible = false;
            //}

            if (SessionUser.BranchID != Branches.CurrentBranchID || !SessionUser.Purchase)
            {
                btnAddCategory.Enabled = false;
                btnAddProd.Enabled = false;
                btnDeleteProd.Enabled = false;
                btnEditCategory.Enabled = false;
                btnEditProd.Enabled = false;
                btnRemoveCategory.Enabled = false;

                btnAddCategory.OnClientClick = "";
                btnAddProd.OnClientClick = "";
                btnDeleteProd.OnClientClick = "";
                btnEditCategory.OnClientClick = "";
                btnEditProd.OnClientClick = "";
                btnRemoveCategory.OnClientClick = "";
            }
            
            if (!SessionUser.Purchase)
            {
                lstProducts.Columns[5].Visible = false;
                lstProducts.Columns[11].Visible = false;
            }
        }

        public string ProductDetailsKey
        {
            get
            {
                if (ViewState["ProductDetailsKey"] == null)
                    ViewState["ProductDetailsKey"] = Guid.NewGuid().ToString();
                return ViewState["ProductDetailsKey"].ToString();
            }
        }

        public string GetProductDetailsPage()
        {
            return "EditPages/PrintHandler.aspx?key=" + ProductDetailsKey;
        }

        protected void lstProducts_OnProductNameClick(object sender, EventArgs e)
        {
            View_ProductDetails prod = View_ProductDetails.GetAvailableProductDetailsByProductIDLocationID(int.Parse(lstProducts.SelectedValue));
            ProductDetailListCtrl printedList = (ProductDetailListCtrl)LoadControl(@"~/Controls/POSControls/ProductDetailListCtrl.ascx");
            printedList.AllowPaging = false;
            printedList.AllowSelecting = false;
            printedList.AllowSorting = false;
            printedList.SourceObject = prod;
            printedList.Width = new Unit(100, UnitType.Percentage);
            printedList.GridLineStyle = GridLines.Both;
            printedList.GridBorder = BorderStyle.Solid;
            printedList.GridBorderWidth = new Unit(1, UnitType.Pixel);
            printedList.CssClass = "";
            printedList.Refresh();

            lstProducts.Refresh();

            Session[ProductDetailsKey] = printedList;
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showPrintDlg('{0}');", GetProductDetailsPage()), true);
        }

        private void ReloadData()
        {
            Brands brands = Brands.LoadAllActiveBrands();
            Utilities.LoadDropDownList(ddlBrand, brands.DefaultView, Brands.ColumnNames.BrandName, Brands.ColumnNames.ID, "--All--");

            hidSelectedNodeValue.Value = "0";
            CategoryListSessionKey = Guid.NewGuid().ToString();
            CategoryList = Categories.GetAllActiveCategories();


            products = Products.GetAllActiveProducts();
            lstProducts.ProductList = products;
            lstProducts.CategoryList = CategoryList;
        }

        public void gridFilterPaging_OnNeedListControl(Object sender, EventArgs e)
        {
            gridFilterPaging.ListControl = lstProducts;
        }

        public String CategoryListSessionKey
        {
            get { return ViewState["CategoryListSessionKey"] != null ? ViewState["CategoryListSessionKey"].ToString() : ""; }
            set { ViewState["CategoryListSessionKey"] = value; }
        }

        public Categories CategoryList
        {
            get { return Session[CategoryListSessionKey] != null ? (Categories)Session[CategoryListSessionKey] : null; }
            set { Session[CategoryListSessionKey] = value; }
        }

        public string GetCategoryEditPageLink()
        {
            return "EditPages/EditCategory.aspx?key=" + CategoryListSessionKey + "&pkey=" + lstProducts.SourceObjectSessionID;
        }

        public string GetProductEditPageLink()
        {
            return "EditPages/EditProduct.aspx?key=" + lstProducts.SourceObjectSessionID;
        }

        public string PrintKey
        {
            get 
            {
                if (ViewState["PrintKey"] == null)
                    ViewState["PrintKey"] = Guid.NewGuid().ToString();
                return ViewState["PrintKey"].ToString();
            }
        }

        public string GetPrintPage()
        {
            return "EditPages/PrintHandler.aspx?key=" + PrintKey;
        }

        protected void btnPrintProduct_OnClick(object sender, EventArgs e)
        {
            ProductListCtrl printedList = (ProductListCtrl)LoadControl(@"~/Controls/POSControls/ProductListCtrl.ascx");
            printedList.AllowPaging = false;
            printedList.AllowSelecting = false;
            printedList.AllowSorting = false;
            printedList.ProductList = lstProducts.ProductList;
            printedList.CategoryList = CategoryList;
            printedList.Width = new Unit(100, UnitType.Percentage);
            printedList.GridLineStyle = GridLines.Both;
            printedList.GridBorder = BorderStyle.Solid;
            printedList.GridBorderWidth = new Unit(1, UnitType.Pixel);
            printedList.CssClass = "";
            printedList.Refresh();
            if (!SessionUser.Admin)
            {
                printedList.Columns[5].Visible = false;
                printedList.Columns[9].Visible = false;
            }

            Session[PrintKey] = printedList;
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showPrintDlg('{0}');", GetPrintPage()), true);

            lstProducts.Refresh();
        }

        Products products;

        protected void RefreshCategoryTree()
        {
            String selectedId = tvCategory.SelectedNode != null ? tvCategory.SelectedNode.Value : "";

            Hashtable nodeCollection = new Hashtable();
            string oldFilter = CategoryList.Filter;

            CategoryList.Filter = Categories.ColumnNames.Deleted + "=0";
            CategoryList.Sort = Categories.ColumnNames.Level + " asc";
            CategoryList.Rewind();
            tvCategory.Nodes.Clear();
            TreeNode rootNode = new TreeNode("All", "0");
            for (int i = 0; i < CategoryList.RowCount; i++)
            {
                TreeNode newNode = new TreeNode(CategoryList.CategoryName, CategoryList.ID.ToString());
                TreeNode parentNode = rootNode;
                if (!CategoryList.IsColumnNull(Categories.ColumnNames.ParentID) && nodeCollection[CategoryList.ParentID] != null)
                    parentNode = (TreeNode)nodeCollection[CategoryList.ParentID];

                if (newNode.Value == hidSelectedNodeValue.Value)
                    newNode.Selected = true;

                nodeCollection[CategoryList.ID] = newNode;
                parentNode.ChildNodes.Add(newNode);

                CategoryList.MoveNext();
            }

            tvCategory.Nodes.Add(rootNode);
            tvCategory.ExpandAll();
            CategoryList.Filter = oldFilter;
            CategoryList.Sort = "";

            //if (tvCategory.SelectedNode == null)
            //    tvCategory.Nodes[0].Selected = true;

            updateCategory.Update();

            //only refresh list when selected node changed
            if (tvCategory.SelectedNode != null && selectedId != tvCategory.SelectedNode.Value)
            {
                RefreshProductList();

                updateByCat.Update();
            }
        }


        protected void btnAddCategory_OnClick(object sender, EventArgs e)
        {
            RefreshCategoryTree();
        }

        protected void btnRemoveCategory_OnClick(object sender, EventArgs e)
        {
            //string oldFilter = CategoryList.Filter;
            DeleteCategories(tvCategory.SelectedNode);

            CategoryList.Save();

            if (lstProducts.ProductList.RowCount > 0)
            {
                lstProducts.ProductList.Rewind();
                for (int i = 0; i < lstProducts.ProductList.RowCount; i++)
                {
                    lstProducts.ProductList.Deleted = true;
                    lstProducts.ProductList.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                    //lstProducts.ProductList.LastModifiedByUser = 0;
                    lstProducts.ProductList.MoveNext();
                }
                lstProducts.ProductList.Save();
            }

            //CategoryList.Filter = oldFilter;
            RefreshCategoryTree();
        }

        protected void btnAddProduct_OnClick(object sender, EventArgs e)
        {
            lstProducts.Refresh();
        }

        private void RefreshProductList()
        {
            gridFilterPaging.Reset();

            String ids = "";
            if (tvCategory.SelectedNode != null)
                ids = IncludeChildIDs(tvCategory.SelectedNode);

            if (ids != "")
                lstProducts.Filter = Products.ColumnNames.Deleted + "=0 and " + Products.ColumnNames.CategoryID + " in (" + ids + ")";
            else
                lstProducts.Filter = Products.ColumnNames.Deleted + "=0";

            if (ddlBrand.SelectedIndex > 0)
                lstProducts.Filter += " and " + Products.ColumnNames.BrandID + "=" + ddlBrand.SelectedValue;

            string filter = "";

            if(ddlFilter.SelectedValue == "1")
                filter = Products.ColumnNames.IsNewArrival + "= 1";
            else if(ddlFilter.SelectedValue == "2")
                filter = Products.ColumnNames.IsHotProduct + "= 1";
            else if(ddlFilter.SelectedValue == "3")
                filter = Products.ColumnNames.IsHomeProduct + "= 1";
            else if (ddlFilter.SelectedValue == "4")
                filter = Products.ColumnNames.IsDealerOnly + "= 1";

            if(filter != "")
                lstProducts.Filter = "(" + lstProducts.Filter + ") and " + filter;

            gridFilterPaging.DefaultFilter = lstProducts.Filter;
            lstProducts.Refresh();
        }

        protected void btnRemoveProduct_OnClick(object sender, EventArgs e)
        {
            lstProducts.DeleteCheckedItems();
            RefreshProductList();
        }

        String IncludeChildIDs(TreeNode node)
        {
            String str = node.Value;
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {
                str += "," + IncludeChildIDs(node.ChildNodes[i]) + ",";
                while(str.IndexOf(",,") >= 0)
                    str = str.Replace(",,", ",");
            }

            return str;
        }

        void DeleteCategories(TreeNode node)
        {
            String oldCatFilter = CategoryList.Filter;
            CategoryList.Filter = Categories.ColumnNames.ID + "=" + node.Value;
            if (!CategoryList.IsColumnNull(Categories.ColumnNames.IsDefault) && CategoryList.IsDefault)
            {
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("alert('Can not delete a Default category!');", 1), true); 
                CategoryList.Filter = oldCatFilter;
                return;
            }

            if (CategoryList.RowCount > 0)
            {
                CategoryList.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                CategoryList.Deleted = true;
                //CategoryList.LastModifiedByUser = 0;
            }

            for (int i = 0; i < node.ChildNodes.Count; i++)
                DeleteCategories(node.ChildNodes[i]);

            CategoryList.Filter = oldCatFilter;
        }

        protected void btnLoadByCat_OnClick(object sender, EventArgs e)
        {
            RefreshProductList();
        }

        protected void btnSearchProduct_OnClick(object sender, EventArgs e)
        {
            gridFilterPaging.Reset();
            if (gridFilterPaging.DefaultFilter != "")
                lstProducts.Filter = gridFilterPaging.DefaultFilter + " and (" + Products.ColumnNames.ProductName + " LIKE '%" + txtSearchProduct.Text + "%')";
            else
                lstProducts.Filter = Products.ColumnNames.ProductName + " LIKE '%" + txtSearchProduct.Text + "%'";
            lstProducts.Refresh();
        }

        protected void btnReload_OnClick(object sender, EventArgs e)
        {
            ReloadData();

            //refresh after init data
            RefreshCategoryTree();
            lstProducts.Refresh();
        }

        protected void ddlBrand_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshProductList();
            gridFilterPaging.Reset();
        }

        protected void ddlFilter_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshProductList();
        }
        protected void btnExcel_OnClick(object sender, EventArgs e)
        {
            View_Products product = View_Products.LoadAllActiveProducts();
            product.Filter = lstProducts.ProductList.Filter;

            if (!SessionUser.Admin)
            {
                Utilities.ExportToExcel(product, "Product List.xls",
                new String[] { "ProductName", "CategoryName", "BrandName", "BarCode", "Quantity", "DealerPrice", "SalePrice" },
                new String[] { "Product", "Category", "Brand", "BarCode", "Quantity", "DealerPrice", "SalePrice" },
                "Product List");
            }
            else
            {
                Utilities.ExportToExcel(product, "Product List.xls",
                new String[] { "ProductName", "CategoryName", "BrandName", "Cost", "BarCode", "Quantity", "DealerPrice", "SalePrice" },
                new String[] { "Product", "Category", "Brand", "Cost", "BarCode", "Quantity", "DealerPrice", "SalePrice" },
                "Product List");
            }
            
        }
    }
}
